package alg;
import java.util.List;


import data.UserRatingList;

import exception.DataManagerException;

public class SimilaritySurprisalVector extends SimilarityAlgorithm {
	
	@Override
	public double eval(int UserId1,int UserId2,DataManager manager) throws DataManagerException {

		UserRatingList ratingsu1 = manager.getRatings(UserId1);
		UserRatingList ratingsu2 = manager.getRatings(UserId2);
		
		double similarity = 0;
		double den, num_sum1, num_sum2;
		
		
		double surprisalu1;
		double surprisalu2;
		double meanscore;
		double diversity;
		int r1,r2;
		int i;
		int num_commonratings;
		List<Integer> commonratings;
		
		commonratings = ratingsu1.intersect(ratingsu2);
		num_commonratings = commonratings.size();
		
		if (num_commonratings > 0) {
			
			den = 0;
			num_sum1 = 0;
			num_sum2 = 0;
			
			//Calcolo i vettori surprisal:
			i = 0;
			while (i < commonratings.size()) {
				int userid = commonratings.get(i);
				UserRatingList userscore = manager.getScores(userid);
				meanscore = userscore.getMeanRating();
				diversity = userscore.getMeanDiversity();
				r1 = ratingsu1.getRating(userid);
				r2 = ratingsu2.getRating(userid);
				
				surprisalu1 = Math.signum(ratingsu1.getRating(userid)-meanscore)*(Math.log(2*diversity)+Math.abs(r1-meanscore)/diversity);
				surprisalu2 = Math.signum(ratingsu2.getRating(userid)-meanscore)*(Math.log(2*diversity)+Math.abs(r2-meanscore)/diversity);
				
				den += surprisalu1*surprisalu2;
				num_sum1 += surprisalu1*surprisalu1;
				num_sum2 += surprisalu2*surprisalu2;
			}
			similarity = den/(Math.sqrt(num_sum1)*Math.sqrt(num_sum2));
		}

		return similarity;
	}
	
	
}
